package com.zzw.util;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;


/**
 * Created by ZZW on 2016/4/13.
 */
public class UploadUtil {
    public static final int TIME_OUT = 10 * 1000;
    public static final String CHARSET = "UTF-8";

    public static int uploadFile(File file, String requestUrl) {
        int resultCode = 0;

        // 准备请求头所需的数据
        String BOUNDARY = UUID.randomUUID().toString();
        String PREFIX = "--";
        String LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";

        try {
            // 请求头
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("Content-Type", CONTENT_TYPE
                    + ",boundary=" + BOUNDARY);
            conn.setRequestProperty("Connection", "Keep-Alive");

            Log.i("test", "upload start");
            if (file != null) {
                // 写入请求头
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer str = new StringBuffer();
                str.append(PREFIX);
                str.append(BOUNDARY);
                str.append(LINE_END);
                str.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END);
                str.append("Content-Type: application/octet-stream; Charset=" + CHARSET + LINE_END);
                str.append(LINE_END);
                dos.write(str.toString().getBytes());

                // 写入文件
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len;
                while ((len = is.read()) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());

                // 写结束符
                String end = PREFIX + BOUNDARY + PREFIX + LINE_END;
                dos.write(end.getBytes());
                dos.flush(); // 刷新
                Log.i("test", "upload end");

                // 上传成功返回的信息
                resultCode = conn.getResponseCode();
                if (resultCode == 200) {
                    Log.i("test", "upload success");
                    InputStream inputStream = conn.getInputStream();
                    StringBuffer s = new StringBuffer();
                    while ((len = inputStream.read(bytes)) != -1) {
                        s.append(new String(bytes, 0, len, "UTF-8"));
                    }
                    Log.i("test", "result:" + s.toString());
                } else {
                    Log.i("test", "upload fail");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultCode;
    }

}
